const express = require("express");
const md5 = require("blueimp-md5");
const UserModel = require("../models/UserModel");
const RoleModel = require("../models/RoleModel");
const RestModel = require("../models/RestModel");
const SecurityModel = require("../models/SecurityModel");
const realModel = require("../models/realModel");
const areaModel = require("../models/areaModel");
const NucleModel = require("../models/AcidModel");
const { find } = require("../models/UserModel");
const router = express.Router();
// 校验原密码是否正确
router.post("/user/pwd", (req, res) => {
  const body = req.body;

  // console.log(body)
  UserModel.findOne({
    _id: body.userId,
    password: md5(body.password),
  })
    .then((user) => {
      if (!user) {
        res.send({ status: 1, msg: "密码不正确" });
      }
      return res.send({ status: 0, data: user });
    })
    .catch((error) => {
      console.log(error);
    });
});
// 修改密码
router.put("/user/pwd", (req, res) => {
  var id = req.body.userId;
  UserModel.findOne({ _id: id }).then((user) => {
    if (!user) {
      return res.send({ status: 1, msg: "密码不正确" });
    }
    user.password = md5(req.body.password);
    UserModel.findByIdAndUpdate(id, user).then(() =>
      res.send({ status: 0, msg: "修改成功" })
    );
  });
});

// 指定需要过滤的属性
const filter = { password: 0, _v: 0 };
// 获取用户信息
router.get("/login", (req, res) => {
  UserModel.find({}).then((user) => {
    res.send({ status: 0, data: user });
  });
});
// 注册用户
router.post("/enroll", (req, res) => {
  const registrant = req.body;
  console.log(req.body);
  UserModel.findOne({ encrypt: registrant.encrypt }).then((encrypt) => {
    // console.log(encrypt);
    if (encrypt) {
      UserModel.findOne({
        username: registrant.username,
        password: md5(registrant.password),
      }).then((user) => {
        if (!user) {
          UserModel.create({
            username: registrant.username,
            password: md5(registrant.password),
            name: registrant.name,
            phone: registrant.phone,
          })
            .then((use) => {
              res.send({ status: 0, data: use });
            })
            .catch((error) => {
              console.error("添加用户异常", error);
              res.send({ status: 1, msg: "添加角色异常,请稍后再试" });
            });
        } else {
          res.send({ status: 1, msg: "用户存在" });
        }
      });
    } else {
      res.send({ status: 1, msg: "验证失败" });
    }
  });
});
// 获取或添加用户
router.post("/login", (req, res) => {
  const { username, password } = req.body;
  UserModel.findOne({ username, password: md5(password) })
    .then((user) => {
      if (user) {
        res.send({ status: 0, data: user });
      } else {
        UserModel.findOne({ username }).then((user) => {
          if (user) {
            res.send({ status: 1, msg: "用户名或密码不正确" });
          } else {
            res.send({ status: 1, msg: "用户未注册请先注册" });
          }
        });
      }
    })
    .catch((error) => {
      res, send({ status: 1, msg: "登陆异常请重试" });
    });
});
// 接口获取
router.post("/role/login", (req, res) => {
  if (req.body.role_id == "") {
    req.body.role_id = "63097dc98947cd391cd1168b";
  }
  RoleModel.findById({ _id: req.body.role_id }).then((data) => {
    // console.log(data)
    res.send({ status: 0, data: data });
  });
});
// 根据Id获取角色
router.post("/role", (req, res) => {
  RoleModel.findById({ _id: req.body.roleId }).then((data) => {
    res.send({ status: 0, data });
  });
});
// 获取所有角色列表
router.get("/role/list", (req, res) => {
  RoleModel.find()
    .then((roles) => {
      res.send({ status: 0, data: roles });
    })
    .catch((error) => {
      console.log("获取角色异常", error);
      res.send({ status: 1, msg: "获取角色异常,请稍后再试" });
    });
});
// 创建角色
router.post("/role/add", (req, res) => {
  const { name } = req.body;
  RoleModel.create({ name })
    .then((role) => {
      res.send({ status: 0, data: role });
    })
    .catch((error) => {
      console.error("添加角色异常", error);
      res.send({ status: 1, msg: "添加角色异常,请稍后再试" });
    });
});
// 更新角色权限
router.post("/role/update", (req, res) => {
  const role = req.body;
  role.auth_time = Date.now();
  RoleModel.findOneAndUpdate({ _id: role._id }, role)
    .then((oldRole) => {
      // console.log(oldRole);
      res.send({ status: 0, data: { ...oldRole._doc, ...role } });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "更新异常请稍后再试" });
    });
});
// 删除角色
router.delete("/role/delete", (req, res) => {
  const row = req.body;
  RoleModel.findByIdAndDelete({ _id: row._id })
    .then(() => {
      res.send({ status: 0, data: "删除成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "删除异常" });
    });
});
// 按列表获取角色信息
router.post("/role/condition", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  RoleModel.find({})
    .then((roleList) => {
      let count = roleList.length;
      RoleModel.find({})
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((error) => {
      res.send({ status: 1, msg: "获取角色列表失败" });
    });
});
// 获取单个住户信息
router.get("/rest/listone", (req, res) => {
  const { _id } = req.query;
  RestModel.findById({ _id }).then((data) => {
    if (data) {
      res.send({ status: 0, data });
    } else {
      res.send({ status: 1, msg: 获取异常 });
    }
  });
});
// 更新住户信息
router.post("/rest/update", (req, res) => {
  const rest = req.body;
  // console.log(security);
  RestModel.findOneAndUpdate({ _id: rest._id }, rest)
    .then((oldrest) => {
      // console.log(oldSecurity._doc,1);
      res.send({ status: 0, data: { ...oldrest._doc, ...rest } });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "更新异常请稍后再试" });
    });
});
// 获取住户信息
router.post("/rest/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  let serach = req.body["serach"].name || "";
  let adminRest = req.body["serach"].adminName || "";
  var obj = {};
  // console.log(serach);
  // console.log(serach.length);
  if (serach.length != 0) {
    obj = {
      name: serach,
    };
  }
  if (adminRest.length != 0) {
    obj = {
      adminRest: adminRest,
    };
  }
  // console.log(obj);
  RestModel.find(obj)
    .then((restList) => {
      let count = restList.length;
      // console.log(count);
      RestModel.find(obj)
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          // console.log(data);
          res.send({
            status: 0,
            data: { total: count, data },
          });
        });
    })
    .catch((error) => {
      console.log("获取学员列表异常", error);
      res.send({ status: 1, msg: "获取异常" });
    });
});
// 创建住户
router.post("/rest/add", (req, res) => {
  // console.log(req.body);
  areaModel.find({ administer: req.body.plotName }).then((user) => {
    if (user.length != 0) {
      req.body["adminRest"] = user[0].name;
    }
  });
  RestModel.find({ id_number: req.body.id_number }).then((restUser) => {
    // console.log(restUser);
    // console.log(req.body);
    if (restUser.length == 0) {
      RestModel.create({ ...req.body })
        .then((data) => {
          // console.log(data);
          res.send({ status: 0, data });
        })
        .catch((error) => {
          console.log(error);
          res.send({ status: 1, msg: "添加异常" });
        });
    } else {
      res.send({ status: 1, msg: "住户存在" });
    }
  });
});
// 删除住户
router.delete("/rest/delete", (req, res) => {
  RestModel.findByIdAndDelete({ _id: req.body._id })
    .then(() => {
      res.send({ status: 0, data: "删除成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "删除异常" });
    });
});
//根据

// =====================
// 根据分页获取安保信息
router.post("/security/list", (req, res) => {
  // console.log(req.body)
  const { page, size } = req.body;
  SecurityModel.find({})
    .then((list) => {
      let count = list.length;
      SecurityModel.find({})
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((error) => {
      console.log("获取学员列表异常", error);
      res.send({ status: 1, msg: "获取异常" });
    });
});
// 创建安保信息
router.post("/security/add", (req, res) => {
  // console.log(req.body);
  SecurityModel.create({ ...req.body })
    .then((data) => {
      res.send({ status: 0, data: "创建成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "添加异常" });
    });
});
// 删除安保信息
router.delete("/security/delete", (req, res) => {
  // console.log(req.body);
  SecurityModel.findByIdAndDelete({ _id: req.body._id })
    .then(() => {
      res.send({ status: 0, data: "删除成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "删除异常" });
    });
});
// 更新安保权限
router.post("/security/update", (req, res) => {
  const security = req.body;
  // console.log(security);
  security.auth_time = Date.now();
  SecurityModel.findOneAndUpdate({ _id: security._id }, security)
    .then((oldSecurity) => {
      // console.log(oldSecurity._doc,1);
      res.send({ status: 0, data: { ...oldSecurity._doc, ...security } });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "更新异常请稍后再试" });
    });
});
// ======================
// 根据分页获取物业信息
router.post("/real/list", (req, res) => {
  // console.log(req.body)
  const { page, size } = req.body;
  realModel
    .find({})
    .then((list) => {
      let count = list.length;
      realModel
        .find({})
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          // console.log(data)
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((error) => {
      console.log("获取学员列表异常", error);
      res.send({ status: 1, msg: "获取异常" });
    });
});
// 创建物业信息
router.post("/real/add", (req, res) => {
  // console.log(req.body);
  realModel
    .create({ ...req.body })
    .then((data) => {
      res.send({ status: 0, data: "创建成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "添加异常" });
    });
});
// 删除物业信息
router.delete("/real/delete", (req, res) => {
  // console.log(req.body);
  realModel
    .findByIdAndDelete({ _id: req.body._id })
    .then(() => {
      res.send({ status: 0, data: "删除成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "删除异常" });
    });
});
// 更新物业权限
router.post("/real/update", (req, res) => {
  const real = req.body;
  // console.log(real);
  real.auth_time = Date.now();
  realModel
    .findOneAndUpdate({ _id: real._id }, real)
    .then((oldreal) => {
      // console.log(oldreal._doc,1);
      res.send({ status: 0, data: { ...oldreal, ...real } });
    })
    .catch((error) => {
      // console.log(error);
      res.send({ status: 1, msg: "更新异常请稍后再试" });
    });
});
// ==============================
// 获取所有区域列表
router.get("/area/list", (req, res) => {
  areaModel
    .find()
    .then((areas) => {
      res.send({ status: 0, data: areas });
    })
    .catch((error) => {
      console.log("获取角色异常", error);
      res.send({ status: 1, msg: "获取角色异常,请稍后再试" });
    });
});
// 创建区域管理人
router.post("/area/add", (req, res) => {
  const { name, phone, auth_name, administer } = req.body;
  areaModel
    .create({ name, phone, auth_name, administer })
    .then((area) => {
      res.send({ status: 0, data: area });
    })
    .catch((error) => {
      console.error("添加角色异常", error);
      res.send({ status: 1, msg: "添加角色异常,请稍后再试" });
    });
});
// 更新区域数据
router.post("/area/update", (req, res) => {
  const area = req.body;
  area.auth_time = Date.now();
  areaModel
    .findOneAndUpdate({ _id: area._id }, area)
    .then((oldarea) => {
      // console.log(oldarea);
      res.send({ status: 0, data: { ...oldarea._doc, ...area } });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "更新异常请稍后再试" });
    });
});
// 删除区域
router.delete("/area/delete", (req, res) => {
  const row = req.body;
  areaModel
    .findByIdAndDelete({ _id: row._id })
    .then(() => {
      res.send({ status: 0, data: "删除成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "删除异常" });
    });
});
// 按列表获取区域信息
router.post("/area/condition", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  areaModel
    .find({})
    .then((areaList) => {
      let count = areaList.length;
      areaModel
        .find({})
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((error) => {
      res.send({ status: 1, msg: "获取角色列表失败" });
    });
});
// 按条件查询
router.get("/area/inquire", (req, res) => {
  // console.log(req.query);
  const { name } = req.query;
  areaModel
    .find({ name: name })
    .then((data) => {
      console.log(data.length);
      if (data.length) {
        res.send({ status: 0, data });
      } else {
        res.send({ status: 1, msg: "查询人不存在" });
      }
    })
    .catch((error) => {
      res.send({ status: 1, msg: "获取异常" });
    });
});
// 获取用户信息
router.get("/cell/get",(req,res) => {
  UserModel.find({username: {$ne:'admin'}}).then(user => {
    res.send({status:0,data:user})
  }).catch(error => {
    console.log(error)
    res.send({status:1,msg:"获取失败"})
  })
});
// 获取用户信息(根据分页)
router.post("/cell/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  UserModel.find({})
    .then((userList) => {
      let count = userList.length;
      UserModel.find({ username: { $ne: "admin" } })
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((error) => {
      res.send({ status: 1, msg: "获取角色列表失败" });
    });
});
//删除当前用户
router.delete("/cell/delete", (req, res) => {
  const row = req.body;
  UserModel.findByIdAndDelete({ _id: row._id })
    .then(() => {
      res.send({ status: 0, data: "删除成功" });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "删除异常" });
    });
});
// 获取核酸列表(分页)
router.post("/nucleic/list", (req, res) => {
  let page = req.body.page || 1;
  let size = req.body.size || 5;
  NucleModel.find({})
    .then((userList) => {
      let count = userList.length;
      NucleModel.find({})
        .skip((page - 1) * parseInt(size))
        .limit(parseInt(size))
        .exec((err, data) => {
          res.send({ status: 0, data: { total: count, data } });
        });
    })
    .catch((error) => {
      res.send({ status: 1, msg: "获取核酸列表失败" });
    });
});
// 创建核酸列表
router.post("/nucleic/add", (req, res) => {
  const name = req.body.list;
  NucleModel.create({name}).then(user => {
    res.send({status:0,mag:"创建成功"})
  }).catch(error => {
    res.send({status:1,mag:"创建失败"})
  })
});
// 获取核酸列表
router.get("/nucleic/get", (req, res) => {
  NucleModel.find({})
    .then((user) => {
      res.send({ status: 0, data: user });
    })
    .catch((error) => {
      console.log(error);
      res.send({ status: 1, msg: "获取失败" });
    });
});
// 更新
router.post("/nucleic/update",(req,res) => {
  const add = req.body;
  NucleModel.findByIdAndUpdate({_id:add._id},add).then(oldadd => {
    res.send({status:0,msg:'更新成功'})
  }).catch(error => {
    console.log(error);
    res.send({status:1,msg:"更新异常"})
  })
})
// 获取更改内容数据
router.post("/nucleic/find",(req,res) => {
  NucleModel.findById({_id:req.body._id}).then(data => {
    res.send({status:0,data})
  }).catch(error => {
    res.send({status:1,msg:'获取失败'})
  })
})
// 图片上传
require("./file-upload")(router);
module.exports = router;
